import { promisifyQuestion, toCSV, toLog } from './util';
import { calculatorsMap, QUESTIONS_MAP } from './const';
import { ELOAN_TYPE } from './types';


const main = async () => {
  const principalInput = await promisifyQuestion(QUESTIONS_MAP.principal);
  const interestRateInput = await promisifyQuestion(QUESTIONS_MAP.interestRate);
  const loanTermInput = await promisifyQuestion(QUESTIONS_MAP.loanTerm);
  const repaymentDateInput = await promisifyQuestion(QUESTIONS_MAP.repaymentDate);
  const repaymentTypeInput = await promisifyQuestion(QUESTIONS_MAP.repaymentType);

  const invalidInput = [principalInput, interestRateInput, loanTermInput, repaymentDateInput, repaymentTypeInput].find(
    (input) => !input.trim(),
  );

  if (!!invalidInput) {
    console.log('无效输入');
    return false;
  }

  const calculator = calculatorsMap.get(repaymentTypeInput as ELOAN_TYPE);
  if (!calculator) {
    console.log('无效的还款方式');
    return false;
  }

  const calculatedResults = calculator({
    principal: Number(principalInput),
    interestRate: Number(interestRateInput),
    loanTerm: Number(loanTermInput),
    repaymentDate: repaymentDateInput,
  });

  toLog(repaymentTypeInput as ELOAN_TYPE, calculatedResults);
  toCSV(repaymentTypeInput as ELOAN_TYPE, calculatedResults);
};

main();
